<?php

namespace app\backend\services\auth;

use app\backend\model\Admin;
use think\App;
use think\Request;
use think\Response;
use Closure;

class Middleware
{

    /**
     * @var Authority $auth
     */
    private $auth;

    public function __construct(App $app)
    {
        $this->auth = $app->auth;
    }

    /**
     * @param Request $request
     * @param Closure $next
     *
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($request, Closure $next)
    {
        if (session('?admin')) {
            $admin = Admin::find(session('admin.id'));
            $this->auth->setUser($admin)->administrator($admin->id === Admin::ADMIN)->assignRole($admin->roles());
        }

        // 权限校验

        /** @var Response $response */
        $response = $next($request);

        return $response;

    }

}
